﻿/*
' DotNetNuke® - http://www.dotnetnuke.com
' Copyright (c) 2002-2009
' by DotNetNuke Corporation
'
' Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
' documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
' the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
' to permit persons to whom the Software is furnished to do so, subject to the following conditions:
'
' The above copyright notice and this permission notice shall be included in all copies or substantial portions 
' of the Software.
'
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
' DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Data.SqlClient;
using System.Text.RegularExpressions;
using Microsoft.SqlServer.Management.Smo;
using WatiN.Core;
using System.IO;

namespace DotNetNuke.Tests.UI.WatiN.Common
{
    public class WatiNBase
    {
        #region Private Members

        IE ieInstance;
        string siteUrl;
        string dbName;
        bool popUpsEnabled;
        private bool set;
        #endregion

        #region Constructors

        public WatiNBase(IE ieInstance, string siteUrl, string dbName)
        {
            this.ieInstance = ieInstance;
            this.siteUrl = siteUrl;
            this.dbName = dbName;
        }

        #endregion

        #region Protected Properties
        public bool PopUpsEnabled
        {
            set { popUpsEnabled = value; }
            get { return popUpsEnabled; }
        }
        public bool Set
        {
            set { set = value; }
            get { return set; }
        }
        public IE IEInstance
        {
            get
            {
                return ieInstance;
            }
        }

        public string SiteUrl
        {
            get
            {
                return siteUrl;
            }
        }
        public string DBName
        {
            get { return dbName; }
        }

        #endregion

        #region Public Properties
        public Int32 siteVersion 
        { 
            get
            {
                string regexString = @"(?<=localhost/DNN_)\d*";
                Match match = Regex.Match(@siteUrl, regexString);
                if(match.Success)
                {
                    return Convert.ToInt32(match.Value);
                }
                return 000;
            }
        }
        public Element Header { get { return ieInstance.Element(Find.ById("Head")); } }
        public Link LogoLink { get { return ieInstance.Link(Find.ById(new Regex("dnn_dnnLogo_hypLogo", RegexOptions.IgnoreCase))); } }
        public Image LogoImage { get { return ieInstance.Image(Find.ById(new Regex("dnn_dnnLogo_imgLogo", RegexOptions.IgnoreCase))); } }
        public Link RegisterLink { get { return IEInstance.Link(Find.ById(new Regex(@"(dnn_dnnUser_registerLink)|(dnn_USER\d_registerLink)", RegexOptions.IgnoreCase))); } }
        public Link LoginLink { get { return IEInstance.Link(Find.ById(new Regex("(dnn_dnnLogin_loginLink)|(dnn_LOGIN1_loginLink)", RegexOptions.IgnoreCase))); } }
        public Link TermsLink { get { return IEInstance.Link(Find.ById("dnn_dnnTERMS_hypTerms")); } }
        public Link PrivacyLink { get { return IEInstance.Link(Find.ById("dnn_dnnPRIVACY_hypPrivacy")); } }
        public Span CopyrightSpan { get { return IEInstance.Span(Find.ById("dnn_dnnCopyright_lblCopyright")); } }
        public Element Body { get { return ieInstance.Element(Find.ById("Body")); } }

        //Menu Links
        public Div RBAdminMenuDiv { get { return IEInstance.Div(Find.ById(s => s.EndsWith("RibbonBar_adminMenus"))); } }
        public Span MenuNavSpan { get { return IEInstance.Span(Find.ById("dnn_dnnNAV_ctldnnNAVt")); } }
        public Span MenuHomeSpan { get { return IEInstance.Span(Find.ByTitle("Home")); } }
        //Admin and Host Menu Spans are Obsolete - will need to update tests
        public Span MenuAdminSpan { get { return IEInstance.Span(Find.ByText("Admin")); } }
        public Span MenuHostSpan { get { return IEInstance.Span(Find.ByText("HOST")); } }
        public Link HostConsoleLink { get { return RBAdminMenuDiv.Link(Find.ByText(s => s.Contains("Host"))); } }
        public Link AdminConsoleLink { get { return RBAdminMenuDiv.Link(Find.ByText(s => s.Contains("Admin"))); } }

        //Control Panel Elements
        public String RibbonBarID { get { return "_RibbonBar_ControlPanel"; } }
        public String ControlPanelID { get { return "_IconBar.ascx_tblControlPanel";}}
        public Div ControlPanel { get { return IEInstance.Div(Find.ById(new Regex("(dnnCPWrapRight)|(ControlPanelWrapper)|(dnn_ControlPanel)"))); } }
        public TableRow ControlPanelAlt { get { return ieInstance.TableRow(Find.ById("dnn_IconBar.ascx_rowControlPanel")); } }
        public Element ControlPanelElement { get { return ControlPanel.Element(Find.ById(new Regex(@"(dnn_(cp_)?IconBar.ascx_tblControlPanel|dnn_(cp_)?RibbonBar_ControlPanel)"))); } }
        public Div RibbonBarDiv
        {
            get
            {
                if(ControlPanel.Div(Find.ById(new Regex("dnn_(cp_)?RibbonBar_ControlPanel"))).Exists)
                {
                    return ControlPanel.Div(Find.ById(new Regex("dnn_(cp_)?RibbonBar_ControlPanel")));
                }
                return null;
            }
        }
        public RadioButton EditRadioButton { get { return ControlPanel.RadioButton(Find.ByValue("EDIT")); } }
        public RadioButton ViewRadioButton { get { return ControlPanel.RadioButton(Find.ByValue("VIEW")); } }
        public RadioButton LayoutRadioButton { get { return ControlPanel.RadioButton(Find.ByValue("LAYOUT")); } }
        public SelectList ControlPanelModeSelectlist { get { return ieInstance.SelectList(Find.ById(s => s.EndsWith("RibbonBar_ddlMode"))); } }
        public Image MaximiseControlPanelImage { get { return ControlPanel.Image(Find.ByTitle("Maximize")); } }
        public Image MinimiseControlPanelImage { get { return ControlPanel.Image(Find.ByTitle("Minimize")); } }




        #region Page Elements
        public Button YesConfirmationButton
        {
            get
            {
                if(PopUpFrame != null)
                {
                    return PopUpFrame.Button(Find.ByText("Yes"));
                }
                return IEInstance.Button(Find.ByText("Yes"));
            }
        }
        public Button NoConfirmationButton
        {
            get
            {
                if(PopUpFrame != null)
                {
                    return PopUpFrame.Button(Find.ByText("No"));
                }
                return IEInstance.Button(Find.ByText("No"));
            }
        }

        public Div ActionMenuBody
        {
            get { return ieInstance.Div(Find.ByClass(s => s.Contains("dnnActionMenu"))); }
        }
        public Div ContentDiv  
        {  
            get
            {
                if (ieInstance.Div(Find.ById("Content")).Exists)
                {
                    return ieInstance.Div(Find.ById("Content"));
                }
                return ieInstance.Div(Find.ByClass("content_pad"));
            } 
        }
        public Div LeftPaneCell { get { return ieInstance.Div(Find.ById("dnn_LeftPane")); } }
        public Div ContentPane 
        {  
            get
            {
                if (PopUpFrame != null && PopUpFrame.Div(Find.ById("dnn_ContentPane")).Exists)
                {
                    return PopUpFrame.Div(Find.ById("dnn_ContentPane"));
                }
                if (ieInstance.Div(Find.ById("dnn_ContentPane")).Exists)
                {
                    return ieInstance.Div(Find.ById("dnn_ContentPane"));
                }
                return ContentDiv;
            } 
        }
        public TableCell ContentPaneCell { get { return ieInstance.TableCell(Find.ById("dnn_ContentPane")); } }
        public Div RightPaneCell { get { return ieInstance.Div(Find.ById("dnn_RightPane")); } }
        public Div BottomPaneDiv { get { return ieInstance.Div(Find.ById("dnn_BottomPane")); } }
        public Div TopPaneDiv { get { return ieInstance.Div(Find.ById("dnn_TopPane")); } }
        public Div FooterDiv { get { return ieInstance.Div(Find.ById("Footer")); } }
        public Div DefaultModuleContainer { get { return ieInstance.Div(Find.ByClass("c_container c_head_grey")); } }

        public Span MessageSpan
        {
            get
            {
                if(PopUpFrame != null)
                {
                    return PopUpFrame.Span(Find.ById(s => s.EndsWith("lblMessage")));
                }
                return ieInstance.Span(Find.ById(s => s.EndsWith("lblMessage")));
            }
        }
        public SpanCollection AllMessageSpans { get { return ContentPane.Spans.Filter(Find.ById(s => s.EndsWith("lblMessage"))); } }
        public Span ModuleMessageSpan { get { return ieInstance.Div(Find.ById(s => s.EndsWith("ModuleContent"))).Span(Find.ById(s => s.EndsWith("lblMessage"))); } }
        public Span PopUpMessageSpan
        {
            get
            {
                if (PopUpFrame != null)
                {
                    return PopUpFrame.Div(Find.ById(s => s.EndsWith("ModuleContent"))).Span(Find.ById(s => s.EndsWith("lblMessage")));
                }
                return ieInstance.Div(Find.ById(s => s.EndsWith("ModuleContent"))).Span(Find.ById(s => s.EndsWith("lblMessage")));
            }
        }

        public Span ModuleTitleSpan { get { return IEInstance.Span(Find.ById(s => s.EndsWith("dnnTITLE_titleLabel"))); } }
        public Span PopUpTitleSpan 
        {
            get
            {
                 if(PopUpFrame != null)
                 {
                     return ieInstance.Span(Find.ById("ui-dialog-title-iPopUp"));
                 }
                 return ModuleTitleSpan;
            }
        }
        public SpanCollection ModuleTitleSpans { get { return ieInstance.Spans.Filter(Find.ById(s => s.EndsWith("dnnTITLE_titleLabel"))); } }

        //This Collection may not be relevant anymore
        public SpanCollection MessageHeadingSpans { get { return ContentPane.Spans.Filter(Find.ById(s => s.EndsWith("lblHeading"))); } }

        public Image ErrorImage { get { return ContentDiv.Image(Find.ByTitle("Error")); } }
        public ImageCollection ErrorImages { get { return ContentDiv.Images.Filter(Find.ByTitle("Error")); } }

        public Frame PopUpFrame
        {
            get
            {
                if (ArePopUpsEnabled())
                {
                    try
                    {
                        return ieInstance.Frame(Find.ById("iPopUp"));
                    }
                    catch(Exception e)
                    {
                        return null;
                    }
                }
                return null;
            }
        }

        public Element FckEditorScriptElement
        {
            get { return ieInstance.Element(Find.BySrc(s => s.Contains("/HtmlEditorProviders/Fck/fckeditor/editor"))); }
        }

        #endregion

        //IE Security Page
        public Link SecurityOveride { get { return IEInstance.Link(Find.ById("overridelink")); } }
        #endregion

      
       

        #region Certificate Functions
        public void IfSecurityErrorThenBypass()
        {
            if (!IEInstance.Title.Contains("Certificate Error")) return;
            if (SecurityOveride.Exists) SecurityOveride.Click();
        }
        #endregion

        #region Public Methods
        public bool HtmlModuleExistsOnPage(string moduleName, string moduleContent)
        {
            bool exists = false;
            bool contentPresent = false;
            SpanCollection moduleTitleSpans = ContentPane.Spans.Filter(Find.ById(s => s.EndsWith("dnnTITLE_lblTitle")));
            foreach (Span titleSpan in moduleTitleSpans)
            {
                if (titleSpan.InnerHtml.Contains(moduleName))
                {
                    exists = true;
                }
            }
            DivCollection moduleContentDiv = ContentPane.Divs.Filter(Find.ById(s => s.EndsWith("HtmlModule_lblContent")));
            foreach (Div contentDiv in moduleContentDiv)
            {
                if (contentDiv.InnerHtml.Contains(moduleContent))
                {
                    contentPresent = true;
                }
            }
            bool result = exists && contentPresent;
            return result;
        }

        public bool PageContainsErrors()
        {
            bool errors = false;
            if (ErrorImage.Exists)
            {
                foreach (Span msgHeaderSpan in MessageHeadingSpans)
                {
                    if (msgHeaderSpan.InnerHtml.Contains("Error") || msgHeaderSpan.InnerHtml.Contains("error"))
                    {
                        errors = true;
                    }
                }
            }
            return errors;
        }
        
        public bool ArePopUpsEnabled()
        {
            if (!Set)
            {
                Set = true;
                string queryString = "SELECT SettingValue FROM PortalSettings WHERE SettingName = 'EnablePopups'";
                //Create the connection string
                //String dbUser = TestUsers.DBUser.UserName;
                //String dbUserPassword = TestUsers.DBUser.Password;

                //Create connection object and open the connection
                //SqlConnection connection = new SqlConnection(connectionString);
                Server server = new Server(TestEnvironment.DatabaseServer);
                Database db = server.Databases[DBName];
                //connection.Open();
                
                

                //Execute the SQL statement
               // if (connection.State == System.Data.ConnectionState.Open)
               //SqlCommand command = new SqlCommand(queryString);
                var result = db.ExecuteWithResults(queryString);

                    //Close the connection
                    //connection.Close();)
               if (result != null && result.ToString().ToLower().Contains("false"))
               {
                    PopUpsEnabled = false;
               }
               else
               {
                    PopUpsEnabled = true;
               }
            }
            return PopUpsEnabled;
        }

        public Option GetSelectedItemFromSelecList(SelectList selectList)
        {
            OptionCollection options = selectList.Options;
            Option selectedOption = null;
            foreach(Option option in options)
            {
                if (option.GetAttributeValue("selected").Contains("selected") || option.GetAttributeValue("selected").Contains("true"))
                {
                    selectedOption = option;
                }
            }
            return selectedOption;
        }

        public Span GetMenuSpan(string itemName)
        {
            Span result = null;
            SpanCollection menuItems = ieInstance.Spans.Filter(Find.ById(s => s.StartsWith("dnn_dnnNAV_ctldnnNAV")));
            foreach (Span item in menuItems)
            {
                if (item.Text.Equals(itemName))
                {
                    result = item;
                    break;
                }
                continue;
            }
            return result;
        }

        public DivCollection GetAllModuleContainers()
        {
            return ieInstance.Divs.Filter(Find.ByClass(s=>s.Contains("DnnModule")));
        }

        public void DeleteFilesInTestEmails()
        {
            foreach (var file in Directory.GetFiles(TestEnvironment.TestEmailPath))
            {
                File.Delete(file);
            }
        }

        public bool SiteIsUsingIconBar()
        {
            if(RibbonBarDiv == null)
            {
                return true;
            }
            return false;
        }

        #endregion
    }
}